package com.itqianfeng.smartmeeting.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itqianfeng.smartmeeting.entity.User;
import com.itqianfeng.smartmeeting.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
@Component
public class DbUser implements UserDetailsManager, UserDetailsPasswordService {
@Autowired
private UserService userService;
    @Override
    public UserDetails updatePassword(UserDetails userDetails, String s) {
        return null;
    }

    @Override
    public void createUser(UserDetails userDetails) {

    }

    @Override
    public void updateUser(UserDetails userDetails) {

    }

    @Override
    public void deleteUser(String s) {

    }

    @Override
    public void changePassword(String s, String s1) {

    }

    @Override
    public boolean userExists(String s) {
        return false;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("user_name",s);
        User user=userService.getOne(wrapper);
        if (user==null){
            throw new UsernameNotFoundException("用户不存在");
        }else {
            Collection<GrantedAuthority> authorities= new ArrayList<>();
            //加入多个角色，需要多次添加
            authorities.add(new SimpleGrantedAuthority("ROLE_"+user.getUserRole()));
            return  new org.springframework.security.core.userdetails.User(
                    user.getUserName(),
                    user.getPassWord(),
                    user.getUserEnable()==1?true:false,
                    true,
                    true,
                    true,
                    authorities
            );
        }
    }
}
